'use strict';
/**
 * Created by FreezeSoul on 2015/10/17.
 */
define([
        'angular',
        'adConfig',
        'app/modules/dataset/define',
        'app/modules/dataset/services/dataset',
        'app/modules/dataset/directives/unique-code',
        'app/modules/schema/services/schema-tree'
    ],
    function (angular, adConfig) {
        angular.module('ad.dataset')
            .controller('adDataSetEditController', ['$rootScope', '$scope', '$state', '$stateParams', '$q', 'Notification', 'adSchemaTreeService', 'adDataSetService'
                , function ($rootScope, $scope, $state, $stateParams, $q, Notification, schemaService, dataSetService) {

                    $scope.$stateParams = $stateParams;

                    $scope.dataServiceTypes = adConfig.dataServiceTypes;

                    $scope.changeServiceType = function (selectedType) {
                        if (selectedType == 'database') { //直接连接数据库
                            $state.go('editor.schema.dataset-edit.database');
                        }
                        if (selectedType == 'excel') { //EXCEL
                            $state.go('editor.schema.dataset-edit.excel');
                        }
                        if (selectedType == 'service') { //SERVICE
                            $state.go('editor.schema.dataset-edit.service');
                        }
                    };

                    var defaultDefine = {
                        DataServiceType: '',  //数据服务类型
                        DataColumnsMap: [],  //数据模型列映射
                        DataServiceMeta: {}  //数据服务元数据
                    };

                    $scope.gotoDefault = function () {
                        $rootScope.$broadcast('ad.message.pathinfo', '模型管理');
                        $state.go("editor.schema.dataset")
                    };

                    $scope.gotoSchema = function () {
                        $rootScope.$broadcast('ad.message.pathinfo', '模型管理');
                        $state.go('editor.schema.schema-edit', {schemaid: $scope.$stateParams.schemaid});
                    };


                    $scope.loadDataSet = function () {
                        var deferred = $q.defer();
                        if ($scope.$stateParams.datasetid == 0) {
                            $scope.dataSet = {
                                dataset_id: 0,
                                dataset_code: '',
                                dataset_name: '新增数据集',
                                dataset_data: '',
                                schema_id: $scope.$stateParams.schemaid
                            };
                            $scope.dataset_defines = defaultDefine;

                            deferred.resolve();
                        } else {
                            dataSetService.loadDataSetById($scope.$stateParams.datasetid).then(function (data) {
                                var obj = angular.fromJson(data);
                                if (obj.result == 'success') {
                                    $scope.dataSet = obj.data;
                                    var jsondata = obj.data.dataset_data;
                                    if (jsondata) {
                                        $scope.dataset_defines = angular.fromJson(jsondata);
                                        $scope.changeServiceType($scope.dataset_defines.DataServiceType);
                                        deferred.resolve();
                                        return;
                                    }
                                    $scope.dataset_defines = defaultDefine;
                                    deferred.resolve();
                                } else {
                                    Notification.error('数据集加载失败！');
                                    deferred.reject();
                                }
                            });
                        }
                        return deferred.promise;
                    };

                    $scope.loadSchema = function () {
                        var deferred = $q.defer();
                        schemaService.loadSchema($scope.$stateParams.schemaid).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                $scope.schema = obj.data;
                                var jsondata = obj.data.schema_data;
                                if (jsondata) {
                                    $scope.schema_columns = angular.fromJson(jsondata);
                                    deferred.resolve();
                                    return;
                                }
                                $scope.schema_columns = [];
                                deferred.resolve();
                            } else {
                                Notification.error('数据模型加载失败！');
                                deferred.reject();
                            }
                        });
                        return deferred.promise;
                    };

                    $scope.save = function () {
                        $scope.dataSet.dataset_data = angular.toJson($scope.dataset_defines);
                        if ($scope.dataSet.dataset_id == 0) {
                            dataSetService.addDataSet($scope.dataSet).then(function (data) {
                                var obj = angular.fromJson(data);
                                if (obj.result == 'success') {
                                    Notification.success('保存成功！');
                                    $rootScope.$broadcast('ad.message.pathinfo', '模型管理');
                                    $state.go('editor.schema.schema-edit', {schemaid: $scope.$stateParams.schemaid});
                                }
                            });
                        } else {
                            dataSetService.updateDataSet($scope.dataSet).then(function (data) {
                                var obj = angular.fromJson(data);
                                if (obj.result == 'success') {
                                    Notification.success('保存成功！');
                                    $rootScope.$broadcast('ad.message.pathinfo', '模型管理');
                                    $state.go('editor.schema.schema-edit', {schemaid: $scope.$stateParams.schemaid});
                                }
                            });
                        }
                    };

                    var promiseDataSet = $scope.loadDataSet();
                    var promiseSchema = $scope.loadSchema();

                    var promises = [];
                    promises.push(promiseSchema);
                    promises.push(promiseDataSet);

                    $q.all(promises).then(function () {
                        //合并映射信息
                        dataSetService.mergeData($scope.dataset_defines.DataColumnsMap,
                            $scope.schema_columns,
                            function (target_item, source_item) {
                                return target_item.Code == source_item.Code;
                            },
                            function (target_item, source_item) {
                                target_item.Name = source_item.Name;
                                target_item.DataType = source_item.DataType;
                                target_item.AnalysisType = source_item.AnalysisType;
                            },
                            function (source_item) {
                                return {
                                    Code: source_item.Code,
                                    Name: source_item.Name,
                                    DataType: source_item.DataType,
                                    AnalysisType: source_item.AnalysisType,
                                    Column: ''
                                }
                            });
                    });

                    $rootScope.$broadcast('ad.schema.selected', $scope.$stateParams.schemaid);
                }]);
    });